package com.unknowpupil.web.utils;

import com.unknowpupil.web.exception.MxException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Classname: JwtUtil
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/10/10 17:20
 * @Description: 这个配置先不限在comment中，写在模块中，不如写死，通用性强，每个模块的加盐可能不同
 * @Version: 1.0
 */
@Component
@ConfigurationProperties("jwt.config")
public class JwtUtil {
    private String key;//加的盐

    private long ttl;//一个小时

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles", roles);
        if (ttl > 0) {
            builder.setExpiration(new Date(nowMillis + ttl*60));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr) throws MxException {
        Claims body = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
        if(body==null){
            throw new MxException("登陆超时，请重写登陆");
        }
        else {
            return body;
        }
    }

}
